package com.boot.project.core.interceptor;

import com.boot.project.core.annotation.AccessLimit;
import com.boot.project.core.enums.code.BaseCode;
import com.boot.project.core.enums.code.impl.commonCode.MicroServiceCode;
import com.boot.project.core.model.result.Result;
import com.boot.project.core.service.CacheService;
import com.boot.project.core.util.IpUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

@Component
public class AccessLimitInterceptor extends HandlerInterceptorAdapter {
 
    @Autowired
    private CacheService cacheService;

    private static ObjectMapper mapper = new ObjectMapper();
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
 
        //判断请求是否属于方法的请求
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            //获取方法中的注解,看是否有该注解
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if (accessLimit == null) {
                return true;
            }
            int seconds = accessLimit.seconds();
            int maxCount = accessLimit.maxCount();
            String key = request.getRequestURI() + IpUtils.getRealIp(request);

            // 从缓存中获取用户访问的次数
            int count = 0;
            Object o = cacheService.get(key);
            if (o == null) {
                cacheService.setAndResetExpireTime(key, 1, seconds * 1000);
            } else {
                count = (int) o;
                // 超出访问限制次数
                if (count == maxCount) {
                    render(response, MicroServiceCode.INVOKING_TOO_FAST); //这里的CodeMsg是一个返回参数
                    return false;
                }
                cacheService.setNotResetExpireTime(key, ++count);
            }
        }
        return true;
    }

    private void render(HttpServletResponse response, BaseCode code) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        String str = mapper.writeValueAsString(Result.failure(code));
        out.write(str.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }
}